package interceptor

import (
	"context"
	"errors"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"mall-backend/pkg/errorex"
	pb "mall-backend/pkg/errorex/grpcerror"
)

func toStatusError(err error) error {
	if err == nil {
		return nil
	}
	var e errorex.Error
	switch {
	case errors.As(err, &e):
		st := status.New(codes.Internal, "Internal")
		pbErr := &pb.Error{
			HttpStatus: int64(e.HttpStatus),
			ErrNo:      int64(e.ErrNo),
			ErrMsg:     e.ErrMsg,
		}
		st, pbe := st.WithDetails(pbErr)
		if pbe != nil {
			return pbe
		}
		return st.Err()
	default:
		return err
	}
}

func ErrorInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,
	handler grpc.UnaryHandler) (resp interface{}, err error) {
	resp, err = handler(ctx, req)
	return resp, toStatusError(err)
}
